"""
应用配置
定义应用的各种配置，如数据库连接、JWT设置等
"""
import os
import datetime
import logging
from pathlib import Path

basedir = os.path.abspath(os.path.dirname(__file__))

class Config:
    """基础配置类"""
    # 基本配置
    VERSION = '0.1.0'
    SECRET_KEY = os.getenv('SECRET_KEY', 'a-very-secret-key')
    DEBUG = False
    TESTING = False
    
    # 日志配置
    LOG_LEVEL = logging.INFO
    
    # 数据库配置
    DB_TYPE = os.getenv('DB_TYPE', 'sqlite')
    DB_USER = os.getenv('DB_USER', 'postgres')
    DB_PASSWORD = os.getenv('DB_PASSWORD', 'postgres')
    DB_HOST = os.getenv('DB_HOST', 'localhost')
    DB_PORT = os.getenv('DB_PORT', '5432')
    DB_NAME = os.getenv('DB_NAME', 'kj_erp')
    
    # SQLAlchemy配置
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ENGINE_OPTIONS = {
        'pool_size': 10,
        'pool_recycle': 3600,
        'pool_pre_ping': True
    }
    
    # JWT配置
    JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY', 'jwt-secret-key')
    JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(hours=1)
    JWT_REFRESH_TOKEN_EXPIRES = datetime.timedelta(days=30)
    JWT_BLACKLIST_ENABLED = True
    JWT_BLACKLIST_TOKEN_CHECKS = ['access', 'refresh']
    
    # CORS配置
    CORS_ORIGINS = os.getenv('CORS_ORIGINS', '*')
    
    # 上传配置
    UPLOAD_FOLDER = os.path.join(basedir, 'uploads')
    MAX_CONTENT_LENGTH = 16 * 1024 * 1024  # 16MB
    
    # Socket.IO配置
    SOCKETIO_ASYNC_MODE = 'eventlet'
    
    # 缓存配置
    CACHE_TYPE = 'SimpleCache'
    CACHE_DEFAULT_TIMEOUT = 300
    
    # 限速配置
    RATELIMIT_ENABLED = True
    RATELIMIT_DEFAULT = "200 per day, 50 per hour"
    RATELIMIT_STORAGE_URL = "memory://"
    
    @property
    def SQLALCHEMY_DATABASE_URI(self):
        """获取数据库URI"""
        if self.DB_TYPE == 'postgres':
            return f"postgresql://{self.DB_USER}:{self.DB_PASSWORD}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"
        else:
            sqlite_path = os.path.join(basedir, '..', f"{self.DB_NAME}.db")
            return f"sqlite:///{sqlite_path}"

class DevelopmentConfig(Config):
    """开发环境配置"""
    DEBUG = True
    LOG_LEVEL = logging.DEBUG
    JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(days=7)  # 开发环境延长令牌过期时间
    SQLALCHEMY_ECHO = True  # 在开发环境中打印SQL语句

class TestingConfig(Config):
    """测试环境配置"""
    DEBUG = True
    TESTING = True
    LOG_LEVEL = logging.DEBUG
    JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(minutes=5)
    WTF_CSRF_ENABLED = False  # 禁用CSRF以便于测试
    
    # 测试使用内存SQLite数据库
    @property
    def SQLALCHEMY_DATABASE_URI(self):
        return "sqlite:///:memory:"

class ProductionConfig(Config):
    """生产环境配置"""
    DEBUG = False
    LOG_LEVEL = logging.WARNING
    
    # 在生产环境中从环境变量获取敏感配置
    SECRET_KEY = os.getenv('SECRET_KEY')
    JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY')
    
    # 生产环境数据库配置
    SQLALCHEMY_ENGINE_OPTIONS = {
        'pool_size': 20,
        'pool_recycle': 3600,
        'pool_pre_ping': True
    }
    
    # 限速配置
    RATELIMIT_DEFAULT = "100 per day, 20 per hour"

# 配置字典
config_by_name = {
    'development': DevelopmentConfig(),
    'testing': TestingConfig(),
    'production': ProductionConfig()
} 